package org.etom.impl.ui.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.ui.WorkbenchException;
import org.etom.connector.datatypes.IMoodleConnection;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.util.ConnectionStorage;
import org.etom.impl.ui.util.Logger;

/**
 * A simple buffer for connections. 
 */
final class ResourcesDataProvider {
  
  private List<IMoodleConnection> connections;
  
  /**
   * Constructs a new resources data provider.
   * The provider will be empty.
   */
  public ResourcesDataProvider() {
    this.connections = new ArrayList<IMoodleConnection>();
  }

  /**
   * The method adds a new connection to the resource provider.
   */
  public void addMoodleConnection(IMoodleConnection connection) {
    addMoodleConnection(connection, true);
  }
  
  private void addMoodleConnection(IMoodleConnection connection, boolean save) {
    if (!connections.contains(connection)) {
      connections.add(connection);
      if (!save) return;
      try {
        save();
      } catch (IOException e) {
        Logger.ERROR(e.getMessage(), e);
      }
    }
  }
  
  /**
   * The method removes the connections.
   * 
   * @param connections - the array is used because we can remove more than one
   * connection at once.
   * 
   * @return true if some connection is removed
   */
  public boolean removeMoodleConnections(IMoodleConnection[] aConnections) {
    if (connections.removeAll(Arrays.asList(aConnections))) {
      try {
        save();
        return true;
      } catch (IOException e) {
        Logger.ERROR(e.getMessage(), e);
        return false;
      }
    }
    return false;
  }
  
  /**
   * The method return the connections in the buffer.
   * 
   * @return available connections
   */
  public List<IMoodleConnection> getMoodleConnections() {
    return connections;
  }
  
  /**
   * The method stores the resource data provider.
   * 
   * @throws IOException - if the resource provider can not be stored
   */
  public void save() throws IOException {
    ConnectionStorage connStorage = Activator.getDefault().getConnectionStorage();
    if (null == connStorage) return;
    connStorage.save(connections.toArray(new IMoodleConnection[connections.size()]));
  }
  
  /**
   * The method loads the resource data provider.
   * 
   * @throws WorkbenchException - if the resource provider can not be loaded
   * @return loaded connections
   */
  public IMoodleConnection[] load() throws WorkbenchException {
    ConnectionStorage connStorage = Activator.getDefault().getConnectionStorage();
    if (null == connStorage) return null;
    IMoodleConnection[] connections = connStorage.load();
    for (IMoodleConnection conn : connections) {
      addMoodleConnection(conn, false);
    }
    return this.connections.toArray(
        new IMoodleConnection[this.connections.size()]);
  }

}
